package com.zzyk.web.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import com.zzyk.main.configuration.aspectj.annotation.OperaLog;
import com.zzyk.main.configuration.exception.DeviceException;
import com.zzyk.main.configuration.exception.UserException;
import com.zzyk.main.controller.BaseController;
import com.zzyk.main.mapper.TestConnectionMapper;
import com.zzyk.main.model.pojo.*;
import com.zzyk.main.model.vo.*;
import com.zzyk.main.mqtt.MyMqttClient;
import com.zzyk.main.service.*;
import com.zzyk.main.utils.HttpUtils;
import com.zzyk.main.utils.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.util.*;

/**
 * @author wss_PC
 * @DESCRIPTION 设备控制器
 * @create 2020-6-16 16:50
 */
@RestController
@RequestMapping("/device")
public class DeviceController extends BaseController {
    /**
     * MQTT服务器地址
     */
    @Value("${mqtt.host}")
    private String host;
    /**
     * MQTT服务器认证用户名
     */
    @Value("${mqtt.username}")
    private String username;
    /**
     * MQTT服务器认证密码
     */
    @Value("${mqtt.password}")
    private String password;
    /**
     * MQTT通信使用字符编码
     */
    @Value("${mqtt.charset}")
    private String charset;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private DeviceUserateService deviceUserateService;
    @Autowired
    private TestConnectionMapper testConnectionMapper;
    @Autowired
    private DeviceParamService deviceParamService;
    @Resource
    private MyMqttClient mqttConnect;
    @Resource
    private VwDeviceProduceService deviceProduceService;
    @Resource
    private RedisUtils redisUtils;

    @GetMapping("/checkThreshold")
    public Message checkThreshold(Integer group,Integer type,Double value) throws MqttException, InterruptedException {
        String parload ;
        if(type.equals(1)){
            parload ="{\"Threshold\":" + value + "}";
        }else {
            parload ="{\"Calibration_P\":1} ";
        }
        try {
            MqttReturn mqttReturn = sendCommand(group, parload);
            if (mqttReturn.getCode() != 0) {
                return Message.failed("发送失败，错误代码：" + mqttReturn.getCode());
            }
            if (type.equals(2)) {
                Thread.sleep(3000);
                parload = "{\"Print_Config\":1}";
                sendCommand(group, parload);
                Device device = deviceService.selectByPrimaryKey(group);
                String clientId = device.getClientId();
                mqttConnect.start(clientId);
                String conf = (String) redisUtils.get(clientId + "_conf");
                int time = 0;
                while (StringUtils.isBlank(conf)) {
                    Thread.sleep(1000);
                    conf = (String) redisUtils.get(clientId + "_conf");
                    time += 1000;
                    if (time ==  1000*60) {
                        return Message.failed("连接失败");
                    }
                }
                JSONObject jsonObject = new JSONObject(conf);
                return Message.success().addData("data", jsonObject.get("Threshold"));
            }
            return Message.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Message.failed();
        } finally {
            if (type.equals(2)) {
                mqttConnect.close();
            }
        }

    }

    @GetMapping("/getDeviceProduceByEnterpise")
    public Message getDeviceProduceByEnterpise() throws UserException {
        SysUser sysUser = currentUser();
        return Message.success().addData("data", deviceProduceService.list(new LambdaQueryWrapper<VwDeviceProduce>().in(VwDeviceProduce::getEnterpise, sysUser.getArea()).isNotNull(VwDeviceProduce::getDeviceType)));
    }

    /**
     * 根据设备编号查询设备信息
     *
     * @param sn   设备编号
     * @param type 设备类型 0采集设备 1生产设备
     * @return
     */
    @GetMapping("/getDeviceBySn")
    public Device getDeviceBySn(String sn, Integer type) throws UserException {
        Device device = deviceService.findDeviceBySnAndType(sn, type);
        SysUser sysUser = currentUser();
        List<String> list = Arrays.asList(sysUser.getArea());
        if (ObjectUtil.isNotNull(device) && list.contains(device.getEnterpise().toString())) {
            return device;
        }
        return null;
    }

    /**
     * 解绑设备
     *
     * @param id
     * @return
     */
    @PostMapping("/unbindDevice")
    public Message unbindDevice(Integer id) {
        return deviceService.unbindDevice(id) ? Message.success() : Message.failed();
    }

    @GetMapping("/getDeviceByDeviceType")
    public Message getDeviceByDeviceType(Integer deviceType) throws UserException {
        SysUser user = currentUser();
        String[] areaArr = user.getArea();
        Integer[] deviceList = user.getDeviceList();
        setPage();
        PageInfo<Device> info = new PageInfo<>(deviceService.selectDeviceByDeviceType(deviceType, areaArr, deviceList));
        return Message.success().addData("data", info.getList())
                .addData("total", info.getTotal())
                .addData("pages", info.getPages());
    }


    /**
     * 根据设备ID获取采集设备参数
     *
     * @param clientId
     * @return
     */
    @GetMapping("/getDeviceParamByDeviceId")
    public Message getDeviceParamByDeviceId(String clientId) {
        return Message.success().addData("data", deviceParamService.selectOneByDeviceId(clientId));
    }

    /**
     * 根据设备ID获取设备信息
     *
     * @param id
     * @return
     */
    @GetMapping("/getDeviceByDid")
    public Device getDeviceByDid(Integer id) {
        return deviceService.selectByPrimaryKey(id);
    }

    /**
     * 获取设备使用率w
     *
     * @return
     */
    @GetMapping("/getDeviceUserate")
    public List<DeviceUserate> getDeviceUserate(Integer id, String beginTime, String endTime, Integer type) {
        return deviceUserateService.findDeviceUserateBuDeviceId(id, beginTime, endTime, type);
    }


    /**
     * 根据企业ID获取生产设备
     *
     * @param id
     * @return
     */
    @GetMapping("/getDeviceByEId")
    public List<Device> getDeviceByEId(Integer id) throws UserException {
        SysUser user = currentUser();
        return deviceService.findDeviceByEId(id, user.getDeviceList());
    }

    /**
     * 根据参数模糊查询(设备名)
     *
     * @param param
     * @return
     */
    @GetMapping("/getDeviceLikeParam")
    public List<Device> getDeviceLikeParam(String param) throws UserException {
        SysUser user = currentUser();
        String[] areaArr = user.getArea();
        Integer[] deviceList = user.getDeviceList();
        return deviceService.findDeviceLikeParam(param, areaArr, deviceList);
    }

    /**
     * 获取GIS页设备信息
     *
     * @param id
     * @return
     */
    @GetMapping("/getGISDeviceInfo")
    public DeviceData getGISDeviceInfo(Integer id) {
        return deviceService.findGISDeviceInfo(id);
    }

    /**
     * 获取用电分析数据
     *
     * @param id
     * @return
     */
    @GetMapping("/getPowerConsumptionStatistics")
    public PowerConsumptionStatistics getPowerConsumptionStatistics(@RequestParam("id") Integer id) {
        return deviceService.findPowerConsumptionStatistics(id);
    }


    /**
     * 获取本月生产时长
     *
     * @param id
     * @return
     */
    @GetMapping("/getProductionTime")
    public List<DateAndString> getProductionTime(Integer id, String beginTime, String endTime, Integer type) {
        return deviceService.findProductionTime(id, beginTime, endTime, type);
    }

    /**
     * 根据时间范围查询功率
     *
     * @param id
     * @return
     */
    @GetMapping("/getRealPowerParam")
    public List<DateAndString> getRealPowerParam(Integer id, String beginTime, String endTime) {

        return deviceService.findRealPowerParam(id, beginTime, endTime, null);
    }

    /**
     * 根据ID查询 实时功率 当天
     *
     * @param id
     * @return
     */
    @GetMapping("/getRealPower")
    public List<DateAndString> getRealPower(Integer id) {

        return deviceService.findRealPower(id);
    }

    /**
     * 根据用户传入的时间范围查询用电量、默认查询一个月。
     *
     * @param id
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/getTodayElectricityByParam")
    public List<DateAndString> getTodayElectricityByParam(Integer id, String beginTime, String endTime) {
        return deviceService.findTodayElectricityByParam(id, beginTime, endTime);
    }

    /**
     * 获取今天用电量
     *
     * @param id
     * @return
     */
    @GetMapping("/getTodayElectricity")
    public List<DateAndString> getTodayElectricity(Integer id) {
        return deviceService.findTodayElectricity(id);
    }

    /**
     * 用电分析更多图表
     *
     * @param id
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/getElectricityAnalysisDataByParam")
    public List<DeviceExtraData> getElectricityAnalysisDataByParam(Integer id, String beginTime, String endTime) {
        return deviceService.findElectricityAnalysisDataByParam(id, beginTime, endTime);
    }

    /**
     * 根据设备ID去查询设备实时数据
     *
     * @param id
     * @return
     */
    @GetMapping("/getElectricityAnalysisData")
    public DeviceExtraData getElectricityAnalysisData(Integer id) {
        return deviceService.findElectricityAnalysisData(id);
    }

    /**
     * 根据采集设备ID获取采集设备信息
     *
     * @return
     */
    @GetMapping("/getDeviceByGroup")
    public Device getDeviceByGroup(Integer group) {
        return deviceService.selectByPrimaryKey(group);
    }

    /**
     * 查询企业下所有的设备
     *
     * @param company
     * @return
     */
    @GetMapping("/getDevicesByCompany")
    public List<Device> getDevicesByCompany(Integer company, Integer id) {
        return deviceService.selectDeviceByCompany(company, id);
    }

    /**
     * 查询企业下所有未绑定设备和当前设备
     *
     * @param company
     * @return
     */
    @GetMapping("/getDevicesByCompanyTwo")
    public List<Device> getDevicesByCompanyTwo(Integer company) {
        return deviceService.selectDeviceByCompanyTwo(company);
    }

    /**
     * 默认获取一个设备
     *
     * @return
     */
    @GetMapping("/getProduceDefaultDevice")
    public Message getProduceDefaultDevice() throws UserException {
        SysUser user = currentUser();
        String[] areaArr = user.getArea();
        Integer[] deviceList = user.getDeviceList();
        if (areaArr.length > 0) {
            return Message.success().addData("data", deviceService.getProduceDefaultDevice(areaArr, deviceList));
        } else {
            return Message.failed("未查询到设备");
        }
    }

    /**
     * 修改设备信息
     *
     * @param device
     * @return
     */
    @PostMapping("/updateCollectionEquipment")
    @OperaLog("修改采集设备信息")
    public Message updateCollectionEquipment(Device device) {
        device.setUpdateTime(DateUtil.parseDateTime(DateUtil.now()));
        deviceService.updateByPrimaryKeySelective2(device);
        return Message.success();
    }

    @PostMapping("/updateDeviceConfig")
    @OperaLog("修改采集设备配置信息")
    public Message updateDeviceConfig(DeviceParam deviceParam) {
        DeviceParam param = deviceParamService.selectOneByDeviceId(deviceParam.getClientID());
        try {
            JSONObject params = JSONUtil.createObj();
            if (ObjectUtil.isNotNull(deviceParam)) {
                /*远程设置供电方式*/
                if (ObjectUtil.isNotNull(deviceParam.getPowerSupply()) && (ObjectUtil.isNull(param) || !deviceParam.getPowerSupply().equals(param.getPowerSupply()))) {
                    params.put("Machine_Type", deviceParam.getPowerSupply());
                }
                /*远程设置时钟*/
                if (StringUtils.isNotBlank(deviceParam.getClock()) && (ObjectUtil.isNull(param) || !deviceParam.getClock().equals(param.getClock()))) {
                    params.put("SET_RTC", deviceParam.getClock());
                }
                /*远程配置上传时间*/
                if (ObjectUtil.isNotNull(deviceParam.getUploadTime()) && (ObjectUtil.isNull(param) || !deviceParam.getUploadTime().equals(param.getUploadTime()))) {
                    params.put("Updata_Time", deviceParam.getUploadTime());
                }
                /*远程配置OUT1*/
                if (ObjectUtil.isNotNull(deviceParam.getOUT1()) && (ObjectUtil.isNull(param) || !deviceParam.getOUT1().equals(param.getOUT1()))) {
                    params.put("OUT1", deviceParam.getOUT1());
                }
                /*远程配置OUT2*/
                if (ObjectUtil.isNotNull(deviceParam.getOUT2()) && (ObjectUtil.isNull(param) || !deviceParam.getOUT2().equals(param.getOUT2()))) {
                    params.put("OUT2", deviceParam.getOUT2());
                }
                /*RS232数据类型*/
                if (ObjectUtil.isNotNull(deviceParam.getRS232()) && (ObjectUtil.isNull(param) || !deviceParam.getRS232().equals(param.getRS232()))) {
                    params.put("RS232Type", deviceParam.getRS232());
                }
                /*远程配置电能表接线方式*/
                if (ObjectUtil.isNotNull(deviceParam.getWiring()) && (ObjectUtil.isNull(param) || !deviceParam.getWiring().equals(param.getWiring()))) {
                    params.put("Wiring_Mode", deviceParam.getWiring());
                }
                /*RS485数据类型*/
                if (ObjectUtil.isNotNull(deviceParam.getRS485()) && (ObjectUtil.isNull(param) || !deviceParam.getRS485().equals(param.getRS485()))) {
                    params.put("RS485Type", deviceParam.getRS485());
                    /*远程控制微断*/
                    if (ObjectUtil.isNotNull(deviceParam.getMicroBreak()) && (ObjectUtil.isNull(param) || !deviceParam.getMicroBreak().equals(param.getMicroBreak()) && deviceParam.getRS485().equals(1))) {
                        params.put("MCCB_Value", deviceParam.getMicroBreak());
                    }
                }
                /*谐波次数*/
                if (ObjectUtil.isNotNull(deviceParam.getHarmonic()) && (ObjectUtil.isNull(param) || !deviceParam.getHarmonic().equals(param.getHarmonic()))) {
                    params.put("Harmonic", deviceParam.getHarmonic());
                }
                /*是否有内置互感器配置*/
                if (ObjectUtil.isNotNull(deviceParam.getTransformer()) && (ObjectUtil.isNull(param) || !deviceParam.getTransformer().equals(param.getTransformer()))) {
                    params.put("Transformer", deviceParam.getTransformer());
                    if (deviceParam.getTransformer().equals(1)) {
                        /*远程配置电能表变流比*/
                        if (ObjectUtil.isNotNull(deviceParam.getVariableFlowRatio()) && (ObjectUtil.isNull(param) || !deviceParam.getVariableFlowRatio().equals(param.getVariableFlowRatio()))) {
                            params.put("IBB", deviceParam.getVariableFlowRatio());
                        }
                        /*设置变压比*/
                        if (ObjectUtil.isNotNull(deviceParam.getTransformationRatio()) && (ObjectUtil.isNull(param) || !deviceParam.getTransformationRatio().equals(param.getTransformationRatio()))) {
                            params.put("VBB", deviceParam.getTransformationRatio());
                        }
                    }
                }
                /*远程配置是否上传*/
                if (ObjectUtil.isNotNull(deviceParam.getNetworkUpload()) && (ObjectUtil.isNull(param) || !deviceParam.getNetworkUpload().equals(param.getNetworkUpload()))) {
                    params.put("UpDataEnable", deviceParam.getNetworkUpload());
                }

            }
            if (params.toJSONString(0).length() > 2) {
                MqttReturn mqttReturn = sendCommand(deviceParam.getDeviceID(), params.toJSONString(0));
                if (mqttReturn.getCode() != 0) {
                    return Message.failed("发送失败，错误代码：" + mqttReturn.getCode());
                }
            }

            /*设置MQTT IP*/
            if (StringUtils.isNotBlank(deviceParam.getMQTTIP()) && (ObjectUtil.isNull(param) || !deviceParam.getMQTTIP().equals(param.getMQTTIP()))) {
                Thread.sleep(5000);
                params.put("MqttIP_SET", deviceParam.getMQTTIP());
                MqttReturn MqttIP_SET = sendCommand(deviceParam.getDeviceID(), "{\"MqttIP_SET\":\"" + deviceParam.getMQTTIP() + "\"}");
                if (MqttIP_SET.getCode() != 0) {
                    return Message.failed("发送失败，错误代码：" + MqttIP_SET.getCode());
                }
            }
            return Message.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Message.failed();
        }
    }

    /**
     * 通过ID查找设备信息，严谨
     *
     * @param id
     * @return
     */
    @GetMapping("/getCollectionEquipmentById")
    public Device getCollectionEquipmentById(Integer id) {
        return deviceService.selectDeviceById(id, 0);
    }

    /**
     * 查询全部采集设备信息
     *
     * @param param
     * @return
     */
    @GetMapping("getCollectionEquipment")
    public Message getCollectionEquipment(String param, Integer bind,Integer status,Integer company) throws UserException {
        SysUser user = currentUser();
        String[] areaArr = user.getArea();
        Integer[] deviceList = user.getDeviceList();
        setPage();
        PageInfo<Device> info = new PageInfo(deviceService.selectCollectionEquipment(param, areaArr, deviceList, bind,status,company));
        return Message.success()
                .addData("data", info.getList())
                .addData("total", info.getTotal())
                .addData("pages", info.getPages());
    }

    /**
     * 添加采集设备信息
     *
     * @param device
     * @return
     */
    @OperaLog("添加采集设备信息")
    @PostMapping("/saveCollectionEquipment")
    public Message saveCollectionEquipment(Device device) {
        try {
            device.setType(0);
            deviceService.insertSelective(device);
            return Message.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Message.failed("保存失败");
        }
    }

    /**
     * 重启单片机系统
     *
     * @param id
     * @return
     */
    @OperaLog("远程重启单片机系统")
    @GetMapping("/restartDevice")
    public Message restartDevice(Integer id) {
        try {
            MqttReturn mqttReturn = sendCommand(id, "{\"Restart\":1}");
            if (mqttReturn.getCode() != 0) {
                return Message.failed("发送失败，错误代码：" + mqttReturn.getCode());
            }
            return Message.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Message.failed();
        }
    }

    private MqttReturn sendCommand(Integer id, String parload) throws UnsupportedEncodingException, MalformedURLException {
        Device device = deviceService.selectByPrimaryKey(id);
        String clientId = device.getClientId();
        String Topid = clientId.substring(0, clientId.length() - 2);

        MqttMessage message = new MqttMessage();
        message.setClient(clientId);
        message.setQos(0);
        message.setRetain(false);
        message.setTopic(Topid + "tx");
        message.setPayload(parload);
        return sendCommand(message);
    }

    /**
     * 远程清零电能表数据
     *
     * @param id
     * @return
     */
    @OperaLog("远程清零电能表数据")
    @GetMapping("/clearElectric")
    public Message clearElectric(Integer id) {
        try {
            MqttReturn mqttReturn = sendCommand(id, "{\"Electric_Clear\":1}");
            if (mqttReturn.getCode() != 0) {
                return Message.failed("发送失败，错误代码：" + mqttReturn.getCode());
            }
            return Message.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Message.failed();
        }
    }

    /**
     * 远程复位报警信号
     *
     * @param id
     * @return
     */
    @OperaLog("发送远程复位报警信号")
    @GetMapping("/remoteResetAlarm")
    public Message remoteResetAlarm(Integer id) {
        try {
            MqttReturn mqttReturn = sendCommand(id, "{\"Rest_Alarm\":1}");
            if (mqttReturn.getCode() != 0) {
                return Message.failed("发送失败，错误代码：" + mqttReturn.getCode());
            }
            return Message.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Message.failed();
        }
    }

    /**
     * 发送mqtt命令
     *
     * @param message
     * @return
     * @throws UnsupportedEncodingException
     * @throws MalformedURLException
     */
    private MqttReturn sendCommand(MqttMessage message) throws UnsupportedEncodingException, MalformedURLException {
        String auth = Base64.getEncoder().encodeToString((username + ":" + password).getBytes(charset));
        String doPost = HttpUtils.doPost(host, JSON.toJSONString(message), auth, Charset.forName(charset));
        cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(doPost);
        return JSONUtil.toBean(jsonObject, MqttReturn.class);
    }

    /**
     * 测试链接采集设备
     *
     * @param number
     * @return
     */
    @GetMapping("/connectionDevice")
    public Message connectionDevice(String number) throws MqttException, InterruptedException {
        number = number.trim();
        String Topid = number.substring(0, number.length() - 2);
        try {
            String substring = number.substring(number.indexOf("/") + 1, number.indexOf("/") + 2);
            MqttMessage message = new MqttMessage();
            message.setClient(number);
            message.setQos(0);
            message.setRetain(false);
            message.setTopic(Topid + "tx");
            if ("4".equals(substring)) {
                message.setPayload("{\"Print_Config\":1}");
            } else {
                message.setPayload("{\"confirmed\":true,\"data\":\"eyJQcmludF9Db25maWciOjF9\",\"fPort\":10}");
            }
            MqttReturn mqttReturn = sendCommand(message);
            if (mqttReturn.getCode() != 0) {
                return Message.failed("连接失败，错误代码：" + mqttReturn.getCode());
            }
            mqttConnect.start(number);
            Thread.sleep(1000);
            String conf = (String) redisUtils.get(number + "_conf");
            int time = 1000;
            while (StringUtils.isBlank(conf)) {
                Thread.sleep(1000);
                conf = (String) redisUtils.get(number + "_conf");
                time += time;
                if (time == 1000*60*4) {
                    return Message.failed("连接失败");
                }
            }
            return Message.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Message.failed();
        } finally {
            mqttConnect.close();
        }
    }

    /**
     * 根据ID删除设备信息
     *
     * @param id
     * @return
     */
    @OperaLog("删除设备信息")
    @GetMapping("/deleteDevice")
    public Message deleteDevice(Integer id) throws DeviceException {
        deviceService.deleteDeviceById(id);
        return Message.success();
    }

    /**
     * 根据ID查询设备信息
     *
     * @param id
     * @return
     */
    @GetMapping("/getProduceDeviceById")
    public Result getProduceDeviceById(Integer id) {
        try {
            return Result.ok(deviceService.selectDeviceById(id, 1));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败");
        }
    }

    /**
     * 生成二维码
     *
     * @return 二维码本地地址
     */
    @GetMapping(value = "/getQrCode", produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] getQrCode(String value) {
        if (StringUtils.isNotBlank(value)) {
            return QrCodeUtil.generatePng(value, 100, 100);
        }
        return null;
    }

    /**
     * 添加设备信息
     *
     * @param device
     * @return
     */
    @OperaLog("添加设备信息")
    @PostMapping("/saveProductionEquipment")
    public Result saveProductionEquipment(Device device) {
        try {
            if (device.getMethodType() == 1) {
                Device device1 = deviceService.selectDeviceByNumber(device.getSn(), 1);
                if (ObjectUtil.isNotNull(device1)) {
                    if (!device1.getId().equals(device.getId())) {
                        return Result.error("该设备编号已存在");
                    }
                }
                device.setUpdateTime(DateUtil.date());
                if (ObjectUtil.isNull(device.getGroup())) {
                    device.setGroup(0);
                }
                deviceService.updateByPrimaryKeySelectiveAndFileUpload(device);
                return Result.ok();
            }
            Device device1 = deviceService.selectDeviceByNumber(device.getSn(), 1);
            if (ObjectUtil.isNotNull(device1)) {
                return Result.error("该设备编号已存在");
            }
            deviceService.addProductionEquipment(device);
            return Result.ok();
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("文件上传失败");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("保存失败");
        }
    }

    /**
     * 采集设备唯一绑定查询
     *
     * @param group
     * @return
     */
    @PostMapping("/uniqueCollectionEquipment")
    public Map<String, Boolean> uniqueCollectionEquipment(Integer group, Integer methodType, Integer id) {
        Map<String, Boolean> map = new HashMap<>(8);
        try {
            if (methodType == 1) {
                Device device = deviceService.selectdeviceByGroup(group);
                if (ObjectUtil.isNotNull(device)) {
                    Device device1 = deviceService.selectByPrimaryKey(id);
                    if (!device.getGroup().equals(device1.getGroup())) {
                        map.put("valid", false);
                        return map;
                    } else {
                        map.put("valid", true);
                        return map;
                    }
                } else {
                    map.put("valid", true);
                    return map;
                }
            }
            Device device = deviceService.selectdeviceByGroup(group);
            if (ObjectUtil.isNull(device)) {
                map.put("valid", true);
                return map;
            }
            map.put("valid", false);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("valid", false);
            return map;
        }


    }

    /**
     * 根据设备编号去查询 设备信息
     *
     * @param sn
     * @return 如果编号已经有了那么就返回true反之为false
     */
    @PostMapping("/verificationDeviceByNumber")
    public Map<String, Boolean> verificationDeviceByNumber(String sn, Integer type) {
        Map<String, Boolean> map = new HashMap<>(8);
        Device device = deviceService.selectDeviceByNumber(sn, type);
        if (ObjectUtil.isNull(device)) {
            map.put("valid", false);
            return map;
        }
        map.put("valid", true);
        return map;
    }

    @PostMapping("verificationDeviceByClientID")
    public Map<String, Boolean> verificationDeviceByClientID(String clientId) {
        Map<String, Boolean> map = new HashMap<>(8);
        Device device = deviceService.selectByClientId(clientId);
        if (ObjectUtil.isEmpty(device)) {
            map.put("valid", true);
            return map;
        }
        map.put("valid", false);
        return map;
    }

    /**
     * 根据设备编号去查询 设备信息
     *
     * @param sn
     * @return 如果编号已经有了那么就返回true反之为false
     */
    @PostMapping("/verificationDeviceByNumber2")
    public Map<String, Boolean> verificationDeviceByNumber2(String sn, Integer type, Integer methodType, Integer id) {
        Map<String, Boolean> map = new HashMap<>(8);
        if (ObjectUtil.isNotEmpty(methodType) && methodType.equals(1)) {
            Device device = deviceService.selectDeviceByNumber(sn, type);
            if (ObjectUtil.isNotNull(device)) {
                if (!device.getId().equals(id)) {
                    map.put("valid", false);
                    return map;
                } else {
                    map.put("valid", true);
                    return map;
                }
            } else {
                map.put("valid", true);
                return map;
            }
        }
        Device device = deviceService.selectDeviceByNumber(sn, type);
        if (ObjectUtil.isNotNull(device)) {
            if (!sn.equals(device.getSn())) {
                map.put("valid", true);
                return map;
            }
            map.put("valid", false);
            return map;
        }
        map.put("valid", true);
        return map;

    }

    /**
     * 统计各个状态的设备信息
     *
     * @return
     */
    @GetMapping("getDeviceByStatus")
    public Message getDeviceByStatus() throws UserException {
        SysUser user = currentUser();
        String[] areaArr = user.getArea();
        Integer[] deviceList = user.getDeviceList();
        try {
            return Message.success().addData("data", deviceService.getDeviceByStatus(null, areaArr, deviceList));
        } catch (Exception e) {
            e.printStackTrace();
            return Message.failed("加载各个状态设备数量失败");
        }
    }

    /**
     * 统计生产设备设备全部数量和各个状态的数量
     *
     * @return
     */
    @GetMapping("getDeviceTotal")
    public Message getDeviceTotal() throws UserException {
        SysUser user = currentUser();
        String[] areas = user.getArea();
        Integer[] group = user.getDeviceList();
        try {
            return Message.success().addData("data", deviceService.getTotal(1, null, areas, group));
        } catch (Exception e) {
            e.printStackTrace();
            return Message.failed("加载企业数量失败");
        }
    }

    /**
     * 获取全部生产设备数据
     *
     * @return
     */
    @GetMapping("/getProductionEquipment")
    public Message getProductionEquipment(String param, @RequestParam(value = "enterprise", required = false) Integer enterprise,Integer bind) throws UserException {
        SysUser user = currentUser();
        String[] areaArr = user.getArea();
        Integer[] deviceList = user.getDeviceList();
        setPage();
        PageInfo<Device> info = null;
        try {
            if (enterprise != null) {
                info = new PageInfo<>(deviceService.selectAllByParam(param, 1, enterprise, areaArr, deviceList,bind));
            } else {
                info = new PageInfo<>(deviceService.selectAllByParam(param, 1, null, areaArr, deviceList,bind));
            }
            return Message.success()
                    .addData("data", info.getList())
                    .addData("total", info.getTotal())
                    .addData("pages", info.getPages());
        } catch (Exception e) {
            e.printStackTrace();
            return Message.failed("加载设备失败");
        }
    }

    @RequestMapping("/getProductionDeviceList")
    public Message getDeviceList(String param) throws UserException {
        SysUser user = currentUser();
        String[] areaArr = user.getArea();
        Integer[] deviceList = user.getDeviceList();
        List<DeviceNode> list = deviceService.getDeviceByEnterpriseId(areaArr, param, deviceList);
        return Message.success().addData("data", list);
    }
}